﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Multithreading3
{
    class ProducerConsumerQueue : IDisposable
    {
        /*
        EventWaitHandle _wh = new AutoResetEvent(false);
        Thread _worker;
        
        Queue<string> _tasks = new Queue<string>();

        public ProducerConsumerQueue()
        {
            _worker = new Thread(Work);
            _worker.Start();
        }

        public void EnqueueTask(string task)
        {
            lock (_locker) _tasks.Enqueue(task);
            _wh.Set();
        }

        public void Dispose()
        {
            EnqueueTask(null);     // Signal the consumer to exit. 
            _worker.Join();         // Wait for the consumer's thread to finish. 
            _wh.Close();            // Release any OS resources. 
        }

        void Work()
        {
            while (true)
            {
                string task = null;
                lock (_locker)
                    if (_tasks.Count > 0)
                    {
                        task = _tasks.Dequeue();
                        if (task == null) return;
                    }
                if (task != null)
                {
                    Console.WriteLine("Performing task: " + task);
                    Thread.Sleep(1000);  // simulate work... 
                }
                else
                    _wh.WaitOne();         // No more tasks - wait for a signal 
            }
        }
        */

        private readonly List<Task> _workers = new List<Task>();
        private List<DateTime> _queue = new List<DateTime>();

        EventWaitHandle _queueEvent = new AutoResetEvent(false);

        readonly object _locker = new object();

        public ProducerConsumerQueue()
        {
            for (var i = 0; i < 10; i++)
            {
                _workers[i] = new Task(Producer);
            }
        }

        public void Producer()
        {
            while (true)
            {
                var dateTimeNow = DateTime.Now;

                lock (_locker)
                {
                    _queue.Add(dateTimeNow);
                    _queueEvent.Set();
                }
            }
        }

        public void Consumer()
        {
            while (true)
            {
                
            }
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
